import {request, Storage, config} from '../util';

const api = config.api;

interface userInfo {
    address?: string,
    name: string,
    token?: string,
    user?: any,
    sessionid?: string
}

class UserService {
    static async getUser() : Promise<userInfo> {
        let name = await Storage.getAsync('name');
        let address = await Storage.getAsync('address');
        let token = await Storage.getAsync('token');
        let user = await Storage.getAsync('user');
        return {
            address,
            name,
            token,
            user
        }
    }

    /**
     * user login
     * @param _name username
     * @param _pwd password
     * @return login success or false
     */
    static async login(name: string, password: string) : Promise<boolean | Object>{
        try {
            let res = await request(api.login, {
                method: 'POST',
                data: {
                    name,
                    password
                }
            }, true);
            let data = res.data;
            if (data.sessionid) {
                UserService.setUser(data);
            }
            
            return data;
        } catch (e) {
            console.error(e);
            UserService.delUser();
            return false;
        }
    }

    static delUser() {
        Storage.delete('name');
        Storage.delete('address');
        Storage.delete('user');
        Storage.delete('token');
    }

    static setUser(data: userInfo) {
        let {name, address, sessionid} = data;
        console.log('setUser.................', name, address, sessionid)
        Storage.set('name', name);
        Storage.set('address', address);
        Storage.set('user', data);
    }

}

export default UserService;